<template>
  <!-- <div class="page-wrap"> -->
    <MenuPage 
      ref="searchTable"
      :data="userList" 
      :columns="userCol"
      :loading="myUserTeamGroupLoading"
      :page.sync="userPage"
      :size.sync="userPageSize"
      :total="userGroupTotal"
      showSelectTag
      :selectName="(user) => {
        return `${user.nickname}${ isCanClick(user) ? '-无删除权限' : '' }`
      }"
      :selection.sync="selectUsers" 
      @queryFun="getCompanyUserList">
      <template slot="search">
        <Button
            ghost
            style="height: 32px;margin-right: 15px"
            type="primary"
            icon="ios-cloud-upload-outline"
            v-if="distributed"
            @click="reportedUsers"
            >人员上报</Button
          >
          <Button
            ghost
            style="height: 32px;margin-right: 15px"
            type="primary"
            icon="ios-cloud-download-outline"
            @click="exportUsers"
            >导出用户</Button
          >
          <Tooltip
            max-width="200"
            content="导入用户会忽略重名和非课件人员的数据，导入的用户未填写登录密码时会被设置为初始密码(Userpw_1234)"
          >
            <Upload
              ref="upload"
              :action="uploadAction"
              :show-upload-list="false"
              :format="['xlsx']"
              :on-format-error="handleFormatError"
              :on-success="getImageUrl"
              :on-progress="handleProgress"
              :before-upload="handleBeforeUpload"
              :headers="uploadHeader"
            >
              <Button ghost style="height: 32px;" type="primary" :disabled="uploadList.length > 0">
                <div v-if="uploadList.length == 0">
                  <Icon type="ios-cloud-upload-outline"></Icon>
                  <span>导入操作员</span>
                </div>
                <div class="demo-upload-list" v-for="item in uploadList">
                  <Progress
                    v-if="item.showProgress"
                    :percent="item.percentage"
                    hide-info
                    style="width:100px"
                  ></Progress>
                </div>
              </Button>
              <!--<p style="position:absolute;color:#f90；">导入用户会忽略重名和非试验人员的数据，所有导入的用户密码都为初始密码</p>-->
            </Upload>
          </Tooltip>
          <Button
            ghost
            style="height: 32px;margin-left: 15px"
            type="primary"
            icon="ios-download-outline"
            ><a href="static/用户模板.xlsx" download="用户模板.xlsx" class="downloadUrl"
              >下载导入操作员模板</a
            ></Button
          >
          <Button
            v-if="selectUsers.length == 0 && mainRangeflag"
            ghost
            style="height: 32px;margin-left: 15px"
            type="error"
            @click="isDeleteList"
            >批量删除</Button
          >
          <Poptip
            v-if="selectUsers.length != 0"
            confirm
            title="确定删除单位人员?"
            @on-ok="deleteList"
            @on-cancel=""
          >
            <Button
              ghost
              style="height: 32px;"
              type="error"
              v-if="selectUsers.length != 0 && mainRangeflag"
              >批量删除</Button
            >
          </Poptip>
<!--          <Button-->
<!--            ghost-->
<!--            style="height: 32px;margin-left: 15px"-->
<!--            type="primary"-->
<!--            class="md-add-jh"-->
<!--            @click="creatGroupMemberBtn"-->
<!--            v-show="!isRootDesigner"-->
<!--            >创建操作员</Button-->
<!--          >-->
<!--        v-show="isRootDesigner"-->
          <Button
            ghost
            style="height: 32px;margin-left: 15px"
            type="primary"
            class="md-add-jh"
            @click="creatDesignBtn"
            
            >创建人员</Button
          >
          <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
          <div style="height: 32px;line-height: 32px;;margin-left: 15px">
            <Checkbox v-model="createByMe" @on-change="searchCreatedByMe" style="width: 66px;"
              >由我创建
            </Checkbox>
          </div>
          <Select filterable
            @on-change="searchItem"
            v-model="rangeId"
            style="width:150px;margin-left:15px"
            placeholder="所属靶场"
            clearable
            v-if="distributedRange && $store.state.common.showDistributed"
          >
            <Option
              v-for="(items, index) in rangeAllList"
              :value="items.id"
              :key="index + 'range'"
              >{{ items.name }}</Option
            >
          </Select>
          <i-select
            v-model="filterRootOrDesi"
            placeholder="类型"
            style="width: 150px;margin-left: 15px"
            @on-change="changeUserType"
          >
            <Option value="all">全部类型</Option>
<!--            <Option value="leader">单位管理员</Option>-->
<!--            <Option value="member">单位设计师</Option>-->

<!--            &lt;!&ndash;<Option value="evaluator">评估人员</Option>&ndash;&gt;-->
<!--            <Option v-if="isRetainer" value="referee">裁判人员</Option>-->
            <Option value="designer">设计师</Option>
            <Option value="experimenter">操作员</Option>
          </i-select>
          <Input
            v-model.trim="searchComMemInput"
            placeholder="用户名"
            clearable
            @on-change="searchComMem"
            style="width: 180px;margin-left: 15px"
          />
          <Input
            v-model.trim="nickname"
            placeholder="昵称"
            clearable
            @on-change="searchComMem"
            style="width: 180px;margin-left: 15px"
          />
          <Input
            v-model.trim="groupName"
            placeholder="实验组"
            clearable
            @on-change="searchComMem"
            style="width: 180px;margin-left: 15px"
          />
          <Button
            class="header-btn"
            type="primary"
            ghost
            style="height: 32px;margin-left: 5px;"
            @click="refreshCompanyUser(true)"
            ><i class="el-icon-refresh-right"
          /></Button>
      </template>

    <!--单位管理员操作-->
    <Modal
      v-model="rootCreatedExpMemberModal"
      :mask-closable="false"
      width="500"
      :footer-hide="true"
      title="创建人员"
    >
      <Form
        ref="rootCreatedExpMemberModel"
        :model="rootCreatedExpMemberModel"
        :rules="rootCreatedExpMemberRuleValidate"
        :label-width="80"
      >
        <FormItem label="用户名" prop="username">
          <Input v-model.trim="rootCreatedExpMemberModel.username" placeholder="用户名"></Input>
        </FormItem>
        <FormItem label="密码" prop="password">
          <Input
            v-model.trim="rootCreatedExpMemberModel.password"
            type="password"
            placeholder="密码"
          ></Input>
        </FormItem>
        <FormItem label="昵称" prop="nickname">
          <Input v-model.trim="rootCreatedExpMemberModel.nickname" placeholder="昵称"></Input>
        </FormItem>
        <FormItem label="类型" prop="type" v-if="rootCreatedExpMemberModal">
          <Select filterable
            v-model="rootCreatedExpMemberModel.type"
            @on-change="changeCreatType"
            placeholder="select"
          >
            <Option value="designer">单位设计师</Option>

            <!--<Option value="evaluator">评估人员</Option>-->
<!--            <Option v-if="isRetainer" value="referee">裁判人员</Option>-->
            <Option value="experimenter">操作员</Option>
          </Select>
        </FormItem>
        <FormItem label="角色" prop="roleId">
          <Select filterable v-model="rootCreatedExpMemberModel.roleId" placeholder="选择" filterable>
            <Option
                v-for="(item, index) in eRolelist"
                :value="item.id"
                :key="index"
                :title="item.roleName"
            >{{ item.roleName }}</Option
            >
          </Select>
        </FormItem>
        
        
        <FormItem label="课件用户组" v-show="showExpGroupSelect">
          <Select filterable v-model="selectGroup" placeholder="选择" filterable>
            <Option
              v-for="(item, index) in allGroupList"
              :value="item.id"
              :key="index"
              :title="item.name"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="邮箱" prop="email">
          <Input v-model.trim="rootCreatedExpMemberModel.email" placeholder="邮箱"></Input>
        </FormItem>
        <FormItem label="手机号" prop="mobile">
          <Input v-model.trim="rootCreatedExpMemberModel.mobile" placeholder="手机号"></Input>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input
            v-model.trim="rootCreatedExpMemberModel.description"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="描述"
          ></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="rootCreatedExpMemberSubmit('rootCreatedExpMemberModel')"
            >确定</Button
          >
          <Button
            @click="rootCreatedExpMemberReset('rootCreatedExpMemberModel')"
            style="margin-left: 8px"
            >重置</Button
          >
        </FormItem>
      </Form>
    </Modal>
    <!--单位设计师创建操作员-->
    <Modal
      v-model="createdExpMemberModal"
      :mask-closable="false"
      width="500"
      :footer-hide="true"
      title="创建操作员"
    >
      <Form
        ref="createdExpMemberModel"
        :model="createdExpMemberModel"
        :rules="createdExpMemberRuleValidate"
        :label-width="80"
      >
        <FormItem label="用户名" prop="username">
          <Input v-model.trim="createdExpMemberModel.username" placeholder="用户名"></Input>
        </FormItem>
        <FormItem label="密码" prop="password">
          <Input
            v-model.trim="createdExpMemberModel.password"
            type="password"
            placeholder="密码"
          ></Input>
        </FormItem>
        <FormItem label="昵称" prop="nickname">
          <Input v-model.trim="createdExpMemberModel.nickname" placeholder="昵称"></Input>
        </FormItem>
        <FormItem label="角色" prop="roleId">
          <Select filterable v-model="createdExpMemberModel.roleId" placeholder="选择" filterable>
            <Option
                v-for="(item, index) in eRolelist"
                :value="item.id"
                :key="index"
                :title="item.roleName"
            >{{ item.roleName }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="实验组">
          <Select filterable v-model="selectGroup" placeholder="选择" filterable>
            <Option
              v-for="(item, index) in allGroupList"
              :value="item.id"
              :key="index"
              :title="item.name"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="邮箱" prop="email">
          <Input v-model.trim="createdExpMemberModel.email" placeholder="邮箱"></Input>
        </FormItem>
        <FormItem label="手机号" prop="mobile">
          <Input v-model.trim="createdExpMemberModel.mobile" placeholder="手机号"></Input>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input
            v-model.trim="createdExpMemberModel.description"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="描述"
          ></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="createdExpMemberSubmit('createdExpMemberModel')"
            >确定</Button
          >
          <Button @click="createdExpMemberReset('createdExpMemberModel')" style="margin-left: 8px"
            >重置</Button
          >
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="modifyNicknameModal"
      :mask-closable="false"
      width="500"
      title="修改昵称"
      footer-hide
    >
      <Form
        ref="modifyNicknameForm"
        :model="modifyNicknameForm"
        :rules="rootCreatedExpMemberRuleValidate"
        :label-width="80"
      >
        <FormItem label="昵称" prop="nickname">
          <Input v-model.trim="modifyNicknameForm.nickname" placeholder="昵称"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="reNickname()" :loading="loading">确定</Button>
          <!--<Button @click="modifyNicknameForm.nickname == ''" style="margin-left: 8px">重置</Button>-->
        </FormItem>
      </Form>
    </Modal>
    <!-- 修改密码 -->
    <Modal v-model="showChangePass" title="修改密码" width="400" class-name="vertical-center-modal">
      <div>
        <Form ref="newPassword" :model="newPassword" :rules="newPasswordRule">
          <FormItem prop="Password">
            <Input
              type="text"
              placeholder="请输入新密码"
              v-model.trim="newPassword.Password"
              clearable
            ></Input>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button
          type="default"
          @click="
            showChangePass = false;
            newPassword.Password = '';
          "
          >取消</Button
        >
        <Button
          :disabled="
            !/^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,20}$/.test(
              newPassword.Password
            )
          "
          type="primary"
          @click="changePassword('newPassword')"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal
      :mask-closable="false"
      width="800"
      footer-hide
      v-model="abnormalUserModal"
      title="导入异常用户列表"
    >
      <div>
        <Table :columns="abnormalUserCol" :data="abnormalUserList"></Table>
      </div>
    </Modal>
  </MenuPage>
</template>
<script>
const YXURL_Comper = 'https://130.2.1.33';
const YXURL_Train = 'http://130.2.1.31';
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import {
  getCompanyData,
  getCompanyUsersHasGroup,
  getExperiData,
  verifyUserName,
  createUser,
  delCompanyMember,
  resetPwd,
  getPwdBlackList,
  exportUsers,
  exportUsersNew,
  deleteListUser
} from '@/api/company.js';
import { reportedUsers, getRangeAll } from '@/api/reported-data';
import { getAllRoleData } from '@/api/users.js';
import { modifyCompanyUserInfo, changePassword } from '@/api/user.js';
import resourcesReportedMixin from '@/mixin/resources-reported-mixin';
import { debounce } from '@/libs/utils';
export default {
  components: {},
  mixins: [resourcesReportedMixin],
  data() {
    let regUsername = /^[0-9A-Za-z_]{5,18}$/; // 账号是数字 字母 或者下划线的组合
    let regPasswd = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/; // 密码必须包含大小写字母、数字和特殊字符，长度为8-16
    // let regPasswd = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@_$])[A-Za-z\d@_$]{8,16}$/; // 密码必须包含大小写字母、数字和特殊字符(@_$)，长度为8-16
    // let regPasswd = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@_$])[A-Za-z0-9@_$]{8,16}$/; // 后台给的验证规则
    const validateUsername = (rule, value, callback) => {
      if (regUsername.test(value)) {
        callback();
      } else {
        callback(new Error('请输入长度为5-18位的账号,可以使用数字、字母或者下划线'));
      }
    };
    const validatePass = (rule, value, callback) => {
      if (regPasswd.test(value)) {
        callback();
      } else {
        callback(new Error('密码必须包含大写字母，小写字母，数字和特殊字符，长度为8-16位'));
      }
    };
    const validateNickname = (rule, value, callback) => {
      let reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,32}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error('请输入长度为1-32位的昵称,可以使用数字、中英文或者下划线'));
      }
    };
    const validateMobile = (rule, value, callback) => {
      let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (value) {
        if (!myreg.test(value)) {
          callback(new Error('请填写正确的手机号'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      userForm: {
        id: ''
      },
      newPassword: {
        Password: ''
      },
      showChangePass: false,
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      distributed: false,
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      // 表格显示
      showMembersData: false,
      showMembersImg: false,
      eRolelist:[],// 操作员的角色列表
      // 单位
      userGroupTotal: 0,
      userPage: 1,
      userPageSize: 12,
      myUserGroupName: '',
      myUserTeamGroupLoading: false,
      userList: [],
      userCol: [
        {
            type: 'selection',
            width: 60,
            align: 'left'
        },
        { title: '用户名', 
          key: 'username', 
          minWidth: 50, 
          tooltip: true,
          placement:"top-left"
        },
        {
            type: 'link',
            title: '昵称',
            key: 'nickname',
            tooltip: true,
            minWidth: 50,
            placement:"top-left",
            on:{
                click: (data) => {
                  if (
                      (data.creator !== this.USER_ID && !this.isRootDesigner) ||
                      data.role === 'leader'
                  ) {
                      return;
                  }
                  this.modifyNicknameBtn(data);
              },
            },
            disabled: (data) => {
                return (
                    (data.creator !== this.USER_ID && !this.isRootDesigner) ||
                    data.role === 'leader'
                );
            }
        },
        { title: '单位', key: 'companyName', minWidth: 50, tooltip: true },
        { title: '所属靶场', key: 'rangeName', minWidth: 50, tooltip: true,show:this.$store.state.common.showDistributed },
        {
            title: '实验组',
            key: 'experimenterGroupList',
            tooltip: true,
            minWidth: 50,
            filter: (list) => {
                return list.map((group) => group.name).join(',');
            }
        },
        {
            title: '在线',
            key: 'online',
            minWidth: 50,
            filter: (online) => {
                return this.isOnline(online).text;
            },
            setColor: (online) => {
                return this.isOnline(online).color;
            }
        },
        {
          title:'上报状态',
          key:'reportedStatus',
          show:() => {
            return this.distributed
          },
          filter:(reportedStatus) => {
            return reportedStatus == '0'
                ? '上报失败'
                : reportedStatus == '1'
                ? '上报中'
                : reportedStatus == '2'
                ? '上报成功'
                : '未上报'
          },
          setColor:(reportedStatus) => {
            return reportedStatus == '0'
                ? '#ed4014'
                : reportedStatus == '1'
                ? '#ff9900'
                : reportedStatus == '2'
                ? '#19be6b'
                : 'grey'
          },
          disabled:(data) => {
            return !data.reportedMsg
          },
          tooltip:true,
          tooltipKey:'reportedMsg'
        },
        {
            title: '类型',
            key: 'type',
            minWidth: 50,
            tooltip: true,
            filter: (type, data) => {
                return this.handleUserType(data);
            }
        },
        { title: '创建者', key: 'creatorName', minWidth: 50, tooltip: true },
        { title: '创建时间', minWidth: 50, key: 'created', tooltip: true },
        {
            title: '操作',
            key: 'action',
            width: '200',
            opList: [
                {
                    txt: '修改密码',
                    disabled: (data) => {
                      return this.setIsClickModify(data) ? true : false
                    },
                    type:'modify',
                    img:{
                      default:require('../../assets/project/modifys-h.png'),
                      disabled:require('../../assets/project/modifys.png')
                    },
                    on:{
                      click:(data,e) => {
                        this.changePass(data)
                      }
                    }
                },
                {
                    txt: '重置密码',
                    tooltip: true,
                    title: '确定要重置密码吗？',
                    img:{
                      default:require('../../assets/project/resetPwd-h.png'),
                      disabled:require('../../assets/project/resetPwd-d.png')
                    },
                    disabled: (data) => {
                      return  this.setIsClickReset(data)? true :false
                    },
                    on:{
                      click:(data,e) => {
                        this.resetPwd(data)
                      }
                    }
                },
                {
                    txt: '删除',
                    tooltip: true,
                    type: 'delete',
                    title: '确定要删除该成员吗？',
                    disabled: (data) => {
                      return  this.setIsClick(data) ? true : false
                    },
                    on:{
                      click:(data,e) => {
                        this.delGroupMember(data)
                      }
                    }
                }
            ]
        }
      ],
      searchComMemInput: '',
      nickname: '',
      groupName: '',
      filterRootOrDesi: 'all',
      userRole: '',
      userType: '',
      filterMyCreatExpMem: 'all',
      createByMe: false,
      // 单位管理员操作 创建组或者成员
      rootCreatedExpMemberModal: false,
      rootCreatedExpMemberModel: {
        role:'',
        roleId:'',
        username: '',
        password: '',
        type: 'designer',
        online: 'false',
        nickname: '',
        mobile: '',
        email: '',
        description: ''
      },
      rootCreatedExpMemberRuleValidate: {
        username: [
          { required: true, validator: validateUsername, trigger: 'change' },
          {
            type: 'string',
            min: 5,
            max: 18,
            message: '请输入长度为5-18位的账号',
            trigger: 'change'
          }
        ],
        roleId: [
          { required: true, message: '角色不能为空 ', trigger: 'change' },
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'change' },
          { type: 'string', min: 8, max: 20, message: '密码不能为空', trigger: 'change' }
        ],
        nickname: [
          { required: true, validator: validateNickname, trigger: 'change' },
          { type: 'string', min: 1, max: 32, message: '昵称长度为1—32', trigger: 'change' }
        ],
        description: [{ max: 200, message: '说明不能超过200个字母', trigger: 'change' }],
        email: [{ type: 'email', message: '请填写正确的邮箱', trigger: 'change' }],
        mobile: [{ validator: validateMobile, trigger: 'change' }]
      },
      selectGroup: '',
      showExpGroupSelect: false,
      // 设计师创建操作员
      createdExpMemberModal: false,
      createdExpMemberModel: {
        username: '',
        password: '',
        role:'',
        roleId:'',
        type: 'experimenter',
        // online: 'false',
        nickname: '',
        mobile: '',
        email: '',
        description: ''
      },
      newPasswordRule: {
        Password: [
          { required: true, validator: validatePass, trigger: 'change' },
          { type: 'string', min: 8, max: 20, message: '密码不能为空', trigger: 'change' }
        ]
      },
      createdExpMemberRuleValidate: {
        username: [
          { required: true, validator: validateUsername, trigger: 'change' },
          { type: 'string', min: 5, max: 18, message: '名称不能为空 ', trigger: 'change' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'change' },
          { type: 'string', min: 8, max: 20, message: '密码不能为空', trigger: 'change' }
        ],

        roleId: [
          { required: true, message: '角色不能为空 ', trigger: 'change' },
        ],
        nickname: [
          { required: true, validator: validateNickname, trigger: 'change' },
          { type: 'string', min: 1, max: 32, message: '昵称长度为1—32', trigger: 'change' }
        ],
        description: [{ max: 200, message: '说明不能超过200个字母 ', trigger: 'change' }],
        email: [{ type: 'email', message: '邮箱格式错误' }],
        mobile: [{ validator: validateMobile, trigger: 'change' }]
      },
      // 获取所有的课件用户组
      allGroupList: [],
      // 密码黑名单
      pwdBlackList: [],
      // 重置密码img
      // resetImg:require('../../assets/project/resetPwd-h.png'),
      invitaIcon: require('../../assets/project/invita-h.png'),
      memsIcon: require('../../assets/project/mems-h.png'),
      //修改昵称
      modifyNicknameModal: false,
      modifyNicknameForm: {
        nickname: ''
      },
      loading: false,
      //导入报告
      uploadAction: '/api/identity/company/users/import',
      uploadGroupAction: '/api/identity/experimenterGroups/import',
      uploadHeader: {
        Authorization: localStorage.token,
        Accept: '*/*'
      },
      uploadList: [],
      uploaderror: false,
      filename: '',
      selectAllUser: false,
      selectUsers: [],
      //导入失败用户modal
      abnormalUserList: [],
      abnormalUserModal: false,
      abnormalUserCol: [
        {
          title: '用户名',
          key: 'username',
          align: 'left'
        },
        {
          title: '昵称',
          key: 'nickname',
          align: 'left'
        },
        {
          title: '角色',
          key: 'role',
          align: 'left'
        },
        {
          title: '类型',
          key: 'type',
          align: 'left'
        },
        {
          title: '导入失败原因',
          key: 'message',
          align: 'left'
        }
      ],
      isRetainer: true,
      rangeAllList: [],
      rangeId: '',
      local: true,
      mainRangeflag: true
    };
  },
  watch: {
    showChangePass(val) {
      if (!val) {
        this.$refs.newPassword.resetFields();
      }
    }
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.distributed = November.distributed;
    this.isRootDesigner = November.isRootDesigner;
    this.userName = November.userName;
    this.isRetainer = sessionStorage.getItem('isRetainer') === 'true';
    console.log(
      '%c [ this.isRetainer ]',
      'font-size:13px; background:pink; color:#bf2c9f;',
      this.isRetainer
    );
  },
  mounted() {
    // this.setStyle();
    $('.company-page .ivu-divider-horizontal').css({
      margin: 0
    });
    // window.onresize = () => {
    //   this.setStyle();
    // };
    //          let getPage = this.$route.query.page?parseInt(this.$route.query.page):1
    //          this.expPage = getPage
    this.getCompanyUserList();
    this.getGroupByCreatExper();
    // 查询密码黑名单
    this.queryPwdList();
    this.isRetainer = sessionStorage.getItem('isRetainer') === 'true';
    console.log(
      '%c [ this.isRetainer ]',
      'font-size:13px; background:pink; color:#bf2c9f;',
      this.isRetainer
    );
    this.queryAllRange();
  },
  computed: {
    distributedRange() {
      return this.$store.state.user.distributedRange;
    },
    pageTitle () {
      //当前菜单显示名
      return this.$route.meta.title;
    },
  },
  methods: {
    getAllRoleData(userType){

      let November = sessionStorage.getItem('November');
      November = JSON.parse(encryption.SelfUseDecrypt(November));
      let params = {
        order: 'desc',
        pageIndex: 1,
        pageSize: 1000,
        sortBy: 'created',
        systemId: November.systemId,
      }
      params.userType = userType||'experimenter'
      getAllRoleData(params)
      .then((res) => {
        if (res.code === 1) {
         
          this.eRolelist = res.data.items;
          
        }
      })
      .catch((err) => {
        console.log(err);
      });
    },
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 197 + 'px';
      let num = this.fullHeight - 197;
      this.userPageSize = Math.floor(num / 102) || 1;
    },
    // 查询密码黑名单
    queryPwdList() {
      getPwdBlackList()
        .then((res) => {
          if (res.data.code === 1) {
            this.pwdBlackList = res.data.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 单位人员列表
    getCompanyUserList: debounce(function(val) {
      if (this.myUserTeamGroupLoading) {
        //正在请求，有新的请求
        this.hasNoExecuteRequest = true;
        return;
      }
      this.myUserTeamGroupLoading = true;
      let params = {
        pageIndex: this.userPage,
        pageSize: this.userPageSize,
        order: 'desc',
        sortBy: 'created',
        nickname: this.nickname,
        local: this.local
      };
      if (this.searchComMemInput != '') {
        params.username = this.searchComMemInput;
      }
      if (this.groupName != '') {
        params.groupName = this.groupName;
      }
      if (this.userRole != '') {
        params.role = this.userRole;
        params.type = `designer`;
      }
      if (this.userType != '') {
        params.type = this.userType;
      }
      if (this.filterMyCreatExpMem === 'myExpMem') {
        params.creator = this.USER_ID;
      }
      if (this.rangeId) {
        params.rangeId = this.rangeId;
      }
      getCompanyUsersHasGroup(params)
        .then(async (res) => {
          if (res.data.code == 1) {
            let getData = res.data.data;
            this.userGroupTotal = Number(getData.total);
            let items = getData.items;
            await this.getUserGroupStatus_mixins(items).then();
            this.userList = items;
            //console.log(items);
            if (items.length > 0) {
              this.showMembersData = true;
              this.showMembersImg = false;
            } else {
              this.showMembersData = false;
              this.showMembersImg = true;
            }
            if (val == '刷新') {
              this.$Message.success({
                content: '刷新成功',
                duration: 3
              });
            }
            this.userList.forEach((user) => {
              if (this.selectUsers.map((user) => user.id).includes(user.id)) {
                this.$set(user, '_checked', true);
              } else {
                this.$set(user, '_checked', false);
              }
            });
            if (
              this.userList.length > 0 &&
              this.userList.every((user) =>
                this.selectUsers.map((user) => user.id).includes(user.id)
              )
            ) {
              this.selectAllUser = true;
            } else {
              this.selectAllUser = false;
            }
            this.setMainOrBranch(); //通过设置靶场控制按钮
          } else {
            this.showMembersData = false;
            this.showMembersImg = true;
            this.userGroupTotal = 0;
            this.userList = [];
          }
          this.myUserTeamGroupLoading = false;
          if (this.hasNoExecuteRequest) {
            this.userOnChange(1);
            this.hasNoExecuteRequest = false;
          }
        })
        .catch((err) => {
          this.showMembersData = false;
          this.showMembersImg = true;
          this.myUserTeamGroupLoading = false;
          if (this.hasNoExecuteRequest) {
            this.userOnChange(1);
            this.hasNoExecuteRequest = false;
          }
          console.log(err);
        });
    }, 500),
    // 过滤
    userOnChange(val) {
      this.userPage = val;
      this.getCompanyUserList();
    },
    searchComMem(val) {
      this.userPage = 1;
      this.searchComMemInput = this.searchComMemInput;
      this.getCompanyUserList();
    },
    changeUserType(type) {
      this.userPage = 1;
      if (type === 'all') {
        this.userRole = '';
        this.userType = '';
      } else if (type === 'experimenter') {
        this.userRole = '';
        this.userType = type;
      } else {
        this.userRole = type;
        this.userType = '';
      }
      this.getCompanyUserList();
    },
    searchCreatedByMe(val) {
      if (val) {
        this.filterMyCreatExpMem = 'myExpMem';
      } else {
        this.filterMyCreatExpMem = 'all';
      }
      this.userPage = 1;
      this.getCompanyUserList();
    },
    // 设置按钮状态
    setDelCompanyMemBtnStatus(params) {
      // 如果当前是单位管理员 或者该操作员创建者 则可退出
      if (this.isRootDesigner || this.USER_ID === params.row.creator) {
        // 将 单位管理员 和 type为manager管理员的按钮都禁掉
        if (params.row.role === 'leader' || params.row.type === 'manager') {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    },
    // 移除公司成员
    delGroupMember(params) {
      let userid = params.id;
      delCompanyMember(userid)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Message.success('已移除该成员！');
            this.$refs.searchTable.closeItem(params);
            this.userPage =
              this.userList.length == 1 && this.userPage > 1 ? this.userPage - 1 : this.userPage;
            this.getCompanyUserList();
          } else {
            this.$Message.error(res.data.message);
          }
        })
        .catch((err) => {
          console.log(err);
          this.$Message.error('服务链接失败！');
        });
    },
    changePass(Row) {
      console.log(Row);

      this.userForm.id = Row.id;
      this.showChangePass = true;
    },
    // 提交新密码
    changePassword(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let id = this.userForm.id;
          let params = {
            password: this.newPassword.Password
          };
          if (this.newPassword == '' || this.newPassword.length < 6) {
            this.$Message.warning({
              content: '请输入新密码且不低于八位!',
              duration: 3
            });
            return false;
          }
          changePassword(id, params).then((res) => {
            // console.log(res)
            if (res.data.code == 1) {
              this.userForm.id = '';
              this.newPassword.Password = '';
              this.showChangePass = false;
              this.$Message.success({
                content: '修改成功',
                duration: 3
              });
            } else {
              this.$Message.error(res.data.message);
            }
          });
        } else {
          this.$Message.error('请重新输入!');
        }
      });
    },
    // 重置成员密码
    resetPwd(params) {
      let id = params.id;
      resetPwd(id)
        .then((res) => {
          if (res.data.code === 1) {
            this.$Notice.success({
              title: '重置成功',
              render: (h) => {
                return h('span', ['重置后的密码为：', h('a', res.data.data)]);
              },
              duration: 0
            });
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 刷新单位
    refreshCompanyUser(showTip) {
      this.selectUsers = []; //清空已经选择的人员
      this.userPage = 1;
      this.searchComMemInput = '';
      this.filterRootOrDesi = 'all';
      this.rangeId = '';
      this.userRole = '';
      this.userType = '';
      this.nickname = '';
      this.groupName = '';
      this.filterMyCreatExpMem = 'all';
      this.createByMe = false;
      if (showTip) {
        this.getCompanyUserList('刷新');
      } else {
        this.getCompanyUserList();
      }
    },
    // 单位管理员创建
    creatDesignBtn() {
      this.$refs['rootCreatedExpMemberModel'].resetFields();
      this.rootCreatedExpMemberModal = true;
      this.rootCreatedExpMemberModel.username = '';
      this.rootCreatedExpMemberModel.password = '';
      this.rootCreatedExpMemberModel.nickname = '';
      this.rootCreatedExpMemberModel.mobile = '';
      this.rootCreatedExpMemberModel.email = '';
      this.rootCreatedExpMemberModel.description = '';
      this.rootCreatedExpMemberModel.type = 'designer';
      this.showExpGroupSelect = false;
      this.selectGroup = '';
      this.getAllRoleData(this.rootCreatedExpMemberModel.type)
    },
    rootCreatedExpMemberSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          delete this.rootCreatedExpMemberModel.role;
          if (this.rootCreatedExpMemberModel.type === 'designer') {
            this.rootCreatedExpMemberModel.role = 'member';
          }
          this.creatMemCommon(this.rootCreatedExpMemberModel);
        } else {
          this.$Message.error('请完善信息！');
        }
      });
    },
    rootCreatedExpMemberReset(name) {
      this.$refs[name].resetFields();
      this.showExpGroupSelect = false;
      this.selectGroup = '';
    },
    changeCreatType(val) {
      if (val === 'designer' || val === 'evaluator' || val === 'referee') {
        this.showExpGroupSelect = false;
        this.selectGroup = '';
      } else if (val === 'experimenter') {
        this.showExpGroupSelect = true;
      }
      this.getAllRoleData(val)
    },
    // 单位设计师创建操作员
    creatGroupMemberBtn() {
      this.$refs['createdExpMemberModel'].resetFields();
      this.createdExpMemberModal = true;
      this.createdExpMemberModel.description = '';
      this.createdExpMemberModel.email = '';
      this.createdExpMemberModel.mobile = '';
      this.createdExpMemberModel.nickname = '';
      this.createdExpMemberModel.password = '';
      this.createdExpMemberModel.username = '';
      this.selectGroup = '';
      this.getAllRoleData()
    },
    createdExpMemberSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.creatMemCommon(this.createdExpMemberModel);
        } else {
          this.$Message.error('请完善信息！');
        }
      });
    },
    createdExpMemberReset(name) {
      this.$refs[name].resetFields();
    },
    // 创建人员公用接口
    creatMemCommon(val) {
      if (this.pwdBlackList.indexOf(val.password) > -1) {
        this.$Message.info({
          content: '该密码不可使用，请重新输入！',
          duration: 3
        });
        return false;
      }
      // 验证用户名是否重复
      verifyUserName(val.username)
        .then((res) => {
          if (res.data.code === 1) {
            if (res.data.data) {
              this.$Message.error({
                content: '该用户名已被使用！',
                duration: 3
              });
            } else {
              this.realSubmitCreatMember(val);
            }
          } else {
            this.$Message.error({
              content: res.data.data,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    realSubmitCreatMember(val) {
      let copyParams = Object.assign({}, val);
      if (copyParams.type === 'evaluator') {
        copyParams.type = 'designer';
        copyParams.role = 'evaluator';
      } else if (copyParams.type === 'referee') {
        copyParams.type = 'designer';
        copyParams.role = 'referee';
      } else if (copyParams.type === 'experimenter') {
        copyParams.role = 'tester';
      }
      let params = {};
      if (this.selectGroup != '') {
        params.experimenterGroupId = this.selectGroup;
      }
      createUser(params, copyParams)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success('人员创建成功！');
            this.createdExpMemberModal = false;
            this.rootCreatedExpMemberModal = false;
            //this.getCompanyUserList()
            this.refreshCompanyUser();
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.$Message.error('服务器连接失败！');
        });
    },
    // 创建人员使用到的实验组 全部数据
    getGroupByCreatExper() {
      let params = {
        pageIndex: 1,
        pageSize: 2147483646,
        visibility: '',
        order: 'desc',
        sortBy: 'created'
      };
      getExperiData(params)
        .then((res) => {
          if (res.data.code == 1) {
            this.allGroupList = res.data.data.items;
          } else {
            this.allGroupList = [];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    isCanClick(user) {
      if (this.isRootDesigner || this.USER_ID === user.creator || user.role === 'leader') {
        return false;
      } else {
        return true;
      }
    },
    exGroupHandleReset(name) {
      this.$refs[name].resetFields();
    },
    // 计算成员列表index
    handleMemIndex(key) {
      return (this.userPage - 1) * this.userPageSize + key + 1;
    },
    // 是否在线
    // 是否在线
    isOnline(val) {
        let text = '';
        let color = '';
        let obj = {};
        if (val) {
            text = '是';
            color = 'var(--status-yes)';
        } else {
            text = '否';
            color = 'var(--status-no)';
        }
        obj.text = text;
        obj.color = color;
        return obj;
    },
    // 设置可见范围
    setVisibility(val) {
      let obj = {};
      let text = '';
      let color = '';
      if (val === 'share') {
        text = '单位';
        color = '#32CD32';
      } else if (val === 'private') {
        text = '个人';
        color = '#FFA500';
      }
      obj.text = text;
      obj.color = color;
      return obj;
    },
    handleApplyStyle(val) {
      if (val > 0) {
        return {
          height: '18px',
          'line-height': '18px',
          'text-align': 'center',
          'background-color': 'rgb(47, 112, 255)',
          color: '#fff',
          'border-radius': '7px',
          cursor: 'pointer',
          padding: '0 10px'
        };
      }
    },
    setIsClickReset(item) {
      if (
        (item.creator !== this.USER_ID && !this.isRootDesigner) ||
        (item.role === 'leader' && item.id !== this.USER_ID)
      ) {
        return { 'pointer-events': 'none' };
      }
    },
    // 是否可以删除
    setIsClick(item) {
      if ((item.creator !== this.USER_ID && !this.isRootDesigner) || item.role === 'leader') {
        return { 'pointer-events': 'none' };
      }
    },
    setImgSrc(item) {
      if (item.creator !== this.USER_ID && !this.isRootDesigner) {
        return require('../../assets/project/modifys.png');
      } else {
        return require('../../assets/project/modifys-h.png');
      }
    },
    setDelImgSrc(item) {
      if ((item.creator !== this.USER_ID && !this.isRootDesigner) || item.role === 'leader') {
        return require('../../assets/project/delNote-d.png');
      } else {
        return require('../../assets/project/delNote-h.png');
      }
    },
    resetResetImg(item) {
      if (
        (item.creator !== this.USER_ID && !this.isRootDesigner) ||
        (item.role === 'leader' && item.id !== this.USER_ID)
      ) {
        return require('../../assets/project/resetPwd-d.png');
      } else {
        return require('../../assets/project/resetPwd-h.png');
      }
    },
    // 处理人员类型
    handleUserType(item) {

      if (item.type === 'designer') {
        return '设计师';
      } else if (item.type === 'experimenter') {
        return '操作员';
      }

      if (item.type === 'designer' && item.role === 'leader') {
        return '单位管理员';
      } else if (item.type === 'designer' && item.role === 'member') {
        return '单位设计师';
      } else if (item.type === 'experimenter' && item.role === 'tester') {
        return '操作员';
      } else if (item.type === 'designer' && item.role === 'referee') {
        return '裁判人员';
      } else if (item.role == 'redManager') {
        // 以下类型是64环境需要的
        return '红方管理员';
      } else if (item.role == 'blueManager') {
        return '蓝方管理员';
      } else if (item.role == 'resManager') {
        return '资源管理员';
      } else if (item.role == 'redplayer') {
        return '红方成员';
      } else if (item.role == 'blueplayer') {
        return '蓝方成员';
      }
    },
    //修改昵称（liqing-2020-09-02）
    reNickname() {
      this.$refs['modifyNicknameForm'].validate((valid) => {
        if (valid) {
          modifyCompanyUserInfo(this.modifyNicknameForm.id, {
            nickname: this.modifyNicknameForm.nickname
          })
            .then((res) => {
              if (res.data.code == 1) {
                this.$Message.success({
                  content: '修改成功！',
                  duration: 3
                });
                this.getCompanyUserList();
                this.modifyNicknameModal = false;
              } else {
                this.$Message.error(res.data.message);
              }
            })
            .catch((err) => {
              this.$Message.error('修改失败');
            });
        } else {
          this.$Message.error('修改失败');
        }
      });
    },
    //设置修改昵称图标（liqing-2020-09-02）
    setModifyNicknameImgSrc(item) {
      if ((item.creator !== this.USER_ID && !this.isRootDesigner) || item.role === 'leader') {
        return require('../../assets/project/modifys.png');
      } else {
        return require('../../assets/project/modifys-h.png');
      }
    },
    // 设置修改昵称是否可点击（liqing-2020-09-02）
    setIsClickModify(item) {
      if ((item.creator !== this.USER_ID && !this.isRootDesigner) || item.role === 'leader') {
        return { 'pointer-events': 'none' };
      }
    },
    //显示修改昵称modal（liqing-2020-09-02）
    modifyNicknameBtn(item) {
      this.modifyNicknameModal = true;
      this.modifyNicknameForm.id = item.id;
      this.modifyNicknameForm.nickname = item.nickname;
    },
    //导入用户（liqing-2020-10-20）
    handleFormatError() {
      this.uploadList = [];
      this.$Message.warning('文件格式错误');
    },
    handleBeforeUpload(file) {
      this.uploadList = this.$refs.upload.fileList;
      return true;
    },
    handleProgress(event, file, fileList) {},
    getImageUrl(res) {
      this.uploadList = [];
      if (res.code == 1) {
        if (res.data.failedList.length > 0) {
          this.abnormalUserList = res.data.failedList;
          this.abnormalUserModal = true;
        } else {
          this.$Message.info('导入成功');
        }
        this.getCompanyUserList();
      } else {
        this.$Message.warning(res.message);
      }
    },
    isDeleteList() {
      let ids = this.selectUsers.map((user) => user.id).join(',');
      if (ids.length === 0) {
        this.$Message.error('请选择需要删除的单位人员！');
        return false;
      }
    },
    // 批量删除单位人员
    deleteList() {
      let deleteUsers = this.selectUsers.filter((user) => {
        return !((user.creator !== this.USER_ID && !this.isRootDesigner) || user.role === 'leader');
      });
      if (deleteUsers.length == 0) {
        this.$Message.info({
          content: '没有可以删除的用户！',
          duration: 3
        });
        this.selectUsers = [];
        this.getCompanyUserList();
        return;
      }
      let ids = deleteUsers.map((user) => user.id).join(',');
      deleteListUser(ids).then((res) => {
        if (res.data.code == 1) {
          this.selectUsers = [];
          this.$Message.success({
            content: '删除成功！',
            duration: 3
          });
          this.userPage =
            this.userList.length == deleteUsers.length && this.userPage > 1
              ? this.userPage - 1
              : this.userPage;
          this.getCompanyUserList();
        } else {
          this.$Message.error('删除失败！');
        }
      });
    },
    // 上报人员
    reportedUsers() {
      let ids = this.selectUsers.map((user) => user.id);
      if (ids.length == 0) {
        this.$Message.warning('请选择用户');
        return;
      }
      reportedUsers(ids)
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.selectUsers = [];
          this.handleCheckAllUser(false);
          this.$Message.info('上报人员成功');
          this.getCompanyUserList();
        })
        .catch(() => {
          this.$Message.error('上报人员异常');
        });
    },
    //导出用户
    exportUsers() {
      let ids = this.selectUsers.map((user) => user.id);
      if (ids.length == 0) {
        this.$Message.warning('请选择用户');
        return;
      }
      exportUsersNew({ ids })
        .then((data) => {
          if (!data.code) {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data.data);
            downloadElement.href = href;
            downloadElement.download = '用户.xlsx';
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.selectUsers = [];
            this.handleCheckAllUser(false);
          } else {
            this.$Message.error('导出用户失败');
          }
        })
        .catch((error) => {
          this.$Message.error('导出用户失败!');
        });
    },
    //选择导出用户
    handleCheckAllUser(e) {
      this.selectAllUser = e;
      this.userList.forEach((user) => {
        this.checkSingleUser(e, user);
      });
    },
    checkSingleUser(e, user) {
      if (e && !this.selectUsers.map((user) => user.id).includes(user.id)) {
        this.selectUsers.push(user);
      } else if (!e && this.selectUsers.map((user) => user.id).includes(user.id)) {
        let index = this.selectUsers.findIndex((item) => user.id == item.id);
        this.selectUsers.splice(index, 1);
      }
      this.$set(user, '_checked', e);
      if (this.userList.length > 0 && this.userList.every((user) => user._checked === true)) {
        this.selectAllUser = true;
      } else {
        this.selectAllUser = false;
      }
    },
    //查询所有分靶场信息
    queryAllRange() {
      getRangeAll().then((res) => {
        if (res.code === 1) {
          this.rangeAllList = res.data.items;
          res.data.items.forEach((item) => {
            if (item.level== 'LOCAL') {
              this.rangeId = item.id;
            }
          });
        }
      });
    },
    searchItem(val) {
      let res = this.rangeAllList.find((item) => {
        return item.id == val;
      });
      if (res && res.level != 'LOCAL') {
        this.local = false;
        this.getCompanyUserList();
      } else {
        this.local = true;
        this.getCompanyUserList();
      }
    },
    setMainOrBranch() {
      let res = this.rangeAllList.find((item) => {
        return item.id == this.rangeId;
      });
      if (res && res.level != 'LOCAL') {
        this.mainRangeflag = false; // 分靶场
      } else {
        this.mainRangeflag = true; // 主靶场
      }
    }
  }
};
</script>
<style scoped>
.downloadUrl {
  color: #a5a5c6;
}
.downloadUrl:hover {
  /* color: rgb(91, 54, 194); */
}
</style>
